import * as BabelCore from '@babel/standalone'; // 放在浏览器中使用的
import type {BabelFileResult, PluginObj} from "@babel/core";

const babelPlugins: PluginObj[] = []

export function addBabelPlugin(plugin: (babel: typeof BabelCore) => PluginObj) {
  babelPlugins.push(plugin(BabelCore))
}

export function babelTransformCode(
  code: string,
  url: string,
  sourceMaps: boolean | "inline" | "both" | null | undefined = 'inline',
  sourceType: "script" | "module" | "unambiguous" | null | undefined = 'module'
) {
  const babelFileResult: BabelFileResult = BabelCore.transform(code, {
    plugins: babelPlugins,
    "filename": url,
    configFile: false,
    sourceMaps: sourceMaps,
    "presets": [
      [
        "env",
        {
          "targets": "defaults, not ie 11, not ie_mob 11",
          "modules": false,
          "forceAllTransforms": true,
          "shippedProposals": true,
          "loose": true,
          "bugfixes": true
        }
      ]
    ],
    "sourceType": sourceType,
  });
  return babelFileResult.code
}
